<?php
/**
 * @author zhaofei
 * @package 产品管理 
 * @createtime 2014-11-25
 * @updatetime 2014-11-25
 * @ps:暂为最高权限用户
 */
namespace System\Controller;
use Think\Controller;
class ProductsController extends Controller {
	function __construct(){
		parent::__construct();
		$ranks = session('ranks');
		if($ranks!=1){
			$this->error('对不起你没有权限',U('Login/index'));
		}
	}

    public function proClass(){
        $model = M('Products_class'); // 实例化User对象
        $count = $model->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list = $model->order('create_time')->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('list',$list);// 赋值数据集
        $this->assign('page',$show);// 赋值分页输出
        $this->display(); // 输出模板
    }

    public function editClass(){
        if(I('get.id')){
            $val = D('Products_class')->where(array('id'=>I('get.id')))->find();
            $val['pname'] = D('Products')->getClassName($val['id']); 
            $this->assign('val',$val);     
        }
        $data = D('Products_class')->where(array('status'=>1))->order('sort asc')->select();  
        $this->assign('data',$data);
        $this->display();
    }

    public function insert(){
        $data = I('post.');
        if(!$data['name']){
            $this->error('分类名不能为空');
        }
        if(!I('post.id')){
            $data['create_time'] = time();
            $data['ct_by_id'] = session('id');
            $is_has = D('Products_class')->field('name')->
                where(array('name'=>I('post.name')))->find();
            if($is_has){
                $this->error('已经存在');
            }
            $rs = D('Products_class')->add($data);
        }else{
            $data['update_time'] = time();
            $data['up_by_id'] = session('id');
            $rs = D('Products_class')->where(array('id'=>I('post.id')))->save($data);
        }
        
        if($rs){
            $this->success('操作成功',U('proClass'));
        }else{
            $this->error('系统故障');
        }
    }

    public function delClass(){
        $id = I('get.id');
        if(!$id){
            $this->error('参数错误');
        }
        $rs = D('Products_class')->delete($id);
        if($rs){
            $this->success('删除成功',U('proClass'));
        }else{
            $this->error('系统故障');
        }
    }

     public function classStatus(){
        $status = I('get.status');
        $id = I('get.id');
        if(!$id){
            $this->error('参数错误');
        }
        $rs = D('Products_class')->where(array('id'=>$id))
            ->save(array('status'=>$status));
        if($rs){
            $this->success('修改成功',U('proClass'));
        }else{
            $this->error('你可能没修改');
        }
    }


    public function index(){
        $model = M('Products'); // 实例化User对象
        $count = $model->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
        $show = $Page->show();// 分页显示输出
        // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
        $list = $model->order('createtime')->limit($Page->firstRow.','.$Page->listRows)->select();
        $this->assign('list',$list);// 赋值数据集
        $this->assign('page',$show);// 赋值分页输出
        $this->display(); // 输出模板
    }

    public function add(){
        $data = D('Products_class')->order('sort asc')->select();
        $num = count($data);
        for($i=0;$i<$num;$i++) {
            $del = D('Products_class')->where(array('p_id'=>$data[$i]['id']))->find();
            if($del){
                unset($data[$i]);
            }
        }
        if(I('get.id')){
             $products = D('Products')->where(array('id'=>I('get.id')))->find();
             $this->assign('products',$products);
             $currents = D('Products_class')->where(array('id'=>$products['p_id']))->find();
             $this->assign('currents',$currents);

        }
        $this->assign('data',$data);
        $this->display();
    }

    public function addProducts(){
        $data = I('post.');
        if(!$data['name']){
            $this->error('产品名不能为空');
        }
        if(!$data['p_id']){
            $this->error('产品分类必须选择');
        }
        if(!I('post.id')){
            $data['createtime'] = time();
            $is_has = D('Products')->field('name')->
                where(array('name'=>I('post.name')))->find();
            if($is_has){
                $this->error('已经存在该名');
            }
            $rs = D('Products')->add($data);
        }else{
            $rs = D('Products')->where(array('id'=>I('post.id')))->save($data);  
        }

        if($rs){
            $this->success('操作成功',U('index'));
        }else{
            $this->error('系统故障');
        }


    }

     public function delProducts(){
        $id = I('get.id');
        if(!$id){
            $this->error('参数错误');
        }
        $rs = D('Products')->delete($id);
        if($rs){
            $this->success('删除成功',U('index'));
        }else{
            $this->error('系统故障');
        }
    }

    public function getChildClass(){
        if(I('post.id')){
            $id = I('post.id');
            $data = D('Products_class')->where(array('p_id'=>$id))->select();
            if($data){
                $this->ajaxReturn(array('data'=>$data,'status'=>1));
            }else{
                $this->ajaxReturn(array('data'=>$data,'status'=>0));
            }
        }
    }



    //产品导入
    public function importExcel(){
        $return=$this->localUpload(array('xls'));
        if ($return['error']){
            $this->error($return['msg']);
        }else {
            vendor('Spreadsheet');
            $data = new \Spreadsheet_Excel_Reader();
            // 设置输入编码 UTF-8/GB2312/CP936等等
            $data->setOutputEncoding('UTF-8');
            $filename = str_replace('http://'.$_SERVER['HTTP_HOST'],$_SERVER['DOCUMENT_ROOT'],$return['msg']);
            $data->read($filename);
            chmod(str_replace('http://'.$_SERVER['HTTP_HOST'],$_SERVER['DOCUMENT_ROOT'],$return['msg']),0777);
            //
            chmod($filename,0777);
            //
            $sheet=$data->sheets[0];
            $rows=$sheet['cells'];
            if ($rows){
                $i=0;
                $num=0;
                $time = time();
                foreach ($rows as $r){
                    if ($i!=0){
                        $Two = array();
                        $db=M('Products');
                        $data = array(
                            'name'=>trim($r[1]),
                            'p_id'=>D('ProductsClass')->getIdByCons(array('name'=>trim($r[2]))),
                            'createtime'=>$time,
                        );
                      //  echo D('ProductsClass')->getLastSql();

                        $check=$db->where(array('name'=>$data['name']))->find();
                        if($data['name'] && $data['p_id'] && !$check){
                            $db->add($data);
                            $num++;
                        } 
                    }
                    $i++;
                }
            }
             $this->success('导入产品'.$num.'条',U('index'));
        }
    }


    function localUpload($filetypes=''){
        $config = array(
            'maxSize' => 1024*100,
            'rootPath' => './Uploads/',
            'savePath' => '',
            'saveName' => array('uniqid',''),
            'exts' => $filetypes,
            'autoSub' => true,
            'subName' => array('date','Ymd'),
        );

        $upload = new \Think\Upload($config);
        if (!file_exists($_SERVER['DOCUMENT_ROOT'].'/Uploads') || !is_dir($_SERVER['DOCUMENT_ROOT'].'/Uploads')){
            mkdir($_SERVER['DOCUMENT_ROOT'].'/Uploads',0777);
        }
        $info = $upload->uploadOne($_FILES['name']);

        if(!$info) {// 上传错误提示错误信息
            $error=1;
            $msg=$upload->getError();
        }else{// 上传成功 获取上传文件信息
            $error=0;
            $msg= 'http://'.$_SERVER['HTTP_HOST'].'/Uploads/'.$info['savepath'].$info['savename'];
        }
        return array('error'=>$error,'msg'=>$msg);
    }
     
    



}